<template>
  <div class="app-container">
    <!-- 数据查询区：表单 -->
    <el-form ref="queryRef" :model="queryParams" :inline="true">
      <el-form-item label="类别编码" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入编码"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="parentName">
        <el-select
          v-model="queryParams.categoryName"
          style="width: 200px"
          placeholder="请选择分类"
        >
          <el-option
            v-for="item in parentOptions"
            :key="item.categoryName"
            :label="item.categoryName"
            :value="item.categoryName"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="!multiple"
          @click="handleDeleteBatch"
          >批量删除</el-button
        >
      </el-col>
    </el-row>

    <div>
      <el-table
        :data="categoryList"
        style="width: 100%; margin-bottom: 20px"
        row-key="categoryId"
        border
        lazy
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="categoryName" label="类别名称" sortable />
        <el-table-column prop="categoryId" label="类别ID" sortable />
        <el-table-column prop="parentId" label="父类别ID" sortable />
        <el-table-column prop="createTime" label="创建时间" sortable />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              size="small"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              size="small"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              link
              type="primary"
              icon="View"
              size="small"
              @click="handleView(scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 数据展示区：分页加载 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      style="margin-top: 20px"
      :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增弹框 -->
    <el-dialog v-model="addDialogOpen" title="新增类别" width="500">
      <el-form ref="addFormRef" :model="addForm" :rules="addRules">
        <el-form-item label="类别ID" prop="categoryId">
          <el-input v-model="addForm.categoryId" placeholder="请输入类别ID" />
        </el-form-item>
        <el-form-item label="大类ID" prop="parentId">
          <el-input v-model="addForm.parentId" placeholder="请输入大类ID" />
        </el-form-item>
        <el-form-item label="类别名称" prop="categoryName">
          <el-input
            v-model="addForm.categoryName"
            placeholder="请输入类别名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitAdd">提交</el-button>
      </template>
    </el-dialog>

    <!-- 修改弹框 -->
    <el-dialog v-model="updateDialogOpen" title="修改类别" width="500">
      <el-form ref="updateFormRef" :model="updateForm" :rules="updateRules">
        <el-form-item label="类别ID" prop="categoryId">
          <el-input v-model="updateForm.categoryId" />
        </el-form-item>
        <el-form-item label="大类ID" prop="parentId">
          <el-input v-model="updateForm.parentId" />
        </el-form-item>
        <el-form-item label="类别名称" prop="categoryName">
          <el-input
            v-model="updateForm.categoryName"
            placeholder="请输入类别名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updateDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitUpdate">提交</el-button>
      </template>
    </el-dialog>

    <!-- 删除弹框 -->
    <el-dialog v-model="deleteDialogOpen" title="删除类别" width="500">
      <el-descriptions :column="1">
        <el-descriptions-item label="类别ID">{{
          deleteForm.categoryId
        }}</el-descriptions-item>
        <el-descriptions-item label="类别名称">{{
          deleteForm.categoryName
        }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="deleteDialogOpen = false">取消</el-button>
        <el-button type="danger" @click="handleSubmitDelete">删除</el-button>
      </template>
    </el-dialog>

    <!-- 抽屉 -->
    <el-drawer v-model="drawer" title="类别信息" :with-header="false">
      <el-descriptions :title="categoryTitle" :column="2" border>
        <el-descriptions-item label="类别ID">{{
          category.categoryId
        }}</el-descriptions-item>
        <el-descriptions-item label="父类ID">{{
          category.parentId
        }}</el-descriptions-item>
        <el-descriptions-item label="类别名称">{{
          category.categoryName
        }}</el-descriptions-item>
        <el-descriptions-item label="父类名称">{{
          category.parentName
        }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRef } from "vue";
import { onMounted } from "vue";
import {
  CategoryForm,
  getCategoryById,
  getCategoryByName,
  listCategoryByTree,
  listCategoryByPage,
  deleteCategoryBatch,
  listAllCategory,
  listParent,
  addCategory,
  updateCategory,
  deleteCategory
} from "@/api/category";
import type { CategoryDTO, ParentDTO, QueryParams } from "@/api/category";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";

// 页面加载时，得到列表数据
onMounted(() => {
  getList();
  getParentOptions();
});

/** ------------------数据查询区——表单-------------------- */
// 表单实例
const queryRef = ref<FormInstance>();

// 类别下拉框
const parentOptions = ref<ParentDTO[]>([]);

function getParentOptions() {
  listParent().then(response => {
    // 直接将返回的数组赋值给 parentOptions
    parentOptions.value = response.data;
  });
}

// 查询参数数据
const query = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 5,
  categoryId: undefined,
  categoryName: undefined,
  parentId: undefined,
  parentName: undefined
});

const queryParams = toRef(query); // 推荐统一使用ref

// 数据查询区--> 查询按钮
function handleQuery() {
  queryParams.value.pageNum = 1; // 重置页码
  if (queryParams.value.categoryId) {
    // 根据类别编码查询
    getCategoryById(queryParams.value.categoryId).then(response => {
      categoryList.value = [response.data];
    });
  } else if (queryParams.value.categoryName) {
    // 根据类别名称查询
    getCategoryByName(queryParams.value.categoryName).then(response => {
      categoryList.value = response.data; // 直接赋值返回的列表
    });
  } else if (queryParams.value.parentName) {
    // 根据分类查询
    getCategoryByName(queryParams.value.parentName).then(response => {
      categoryList.value = response.data; // 直接赋值返回的列表
    });
  } else {
    // 如果没有输入任何查询条件，加载全部数据
    getList();
  }
}

// 数据查询区--> 重置按钮
const resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields(); // 重置表单
  getList(); // 重新加载数据
};

/** ------------------数据展示区：数据加载-------------------- */

// 数据列表
const loading = ref<boolean>(false); // table数据加载遮罩
const total = ref<number>(0); // table数据总数
const tableData = reactive<CategoryDTO[]>([]); // table数据
const categoryList = toRef(tableData);

// 数据展示区--> 数据加载
function getList() {
  loading.value = true;
  // 调用分页查询接口
  listCategoryByPage(queryParams.value)
    .then(response => {
      categoryList.value = response.data.list; // 更新表格数据
      total.value = response.data.total; // 更新总数
      loading.value = false;
    })
    .catch(error => {
      console.error("Error fetching data:", error);
      loading.value = false;
      ElMessage.error("查询失败，请稍后再试");
    });
}

/** ------------------数据展示区：分页加载-------------------- */
// 分页--> 修改每页数据数（5｜10｜20｜30）
function handleSizeChange(val: number) {
  queryParams.value.pageSize = val;
  getList();
}

// 分页--> 修改当前页
function handleCurrentChange(val: number) {
  queryParams.value.pageNum = val;
  getList();
}

/** ------------------数据展示区：数据选择-------------------- */
const ids = ref<number[]>([]); // 表单勾选的id
const single = ref<boolean>(false); // 勾选1个
const multiple = ref<boolean>(false); // 勾选多个

// 数据展示区--> 勾选数据
function handleSelectionChange(selection: CategoryDTO[]) {
  ids.value = selection.map((item: CategoryDTO) => item.categoryId);
  single.value = selection.length == 1;
  multiple.value = selection.length >= 1;
}

/** ------------------新增弹框-------------------- */
const addDialogOpen = ref<boolean>(false);
const addForm = ref({
  categoryId: null,
  categoryName: "",
  parentId: null
});
const addFormRef = ref<FormInstance>();
const addRules = reactive({
  categoryId: [{ required: true, message: "类别ID不能为空", trigger: "blur" }],
  categoryName: [
    { required: true, message: "类别名称不能为空", trigger: "blur" }
  ]
});

function handleAdd() {
  addDialogOpen.value = true;
}

function handleSubmitAdd() {
  addFormRef.value?.validate(valid => {
    if (valid) {
      const data = {
        categoryId: addForm.value.categoryId,
        parentId: addForm.value.parentId,
        categoryName: addForm.value.categoryName
      };
      console.log(addForm);
      console.log(data);
      addCategory(data)
        .then(() => {
          ElMessage.success("新增成功");
          addDialogOpen.value = false;
          getList();
        })
        .catch(() => {
          ElMessage.error("新增失败");
        });
    }
  });
}

/** ------------------修改弹框-------------------- */
const updateDialogOpen = ref<boolean>(false);
const updateForm = reactive({
  categoryId: 0,
  parentId: null,
  categoryName: ""
});
const updateFormRef = ref<FormInstance>();
const updateRules = reactive({
  categoryName: [
    { required: true, message: "类别名称不能为空", trigger: "blur" }
  ]
});

const selectedRow = ref<CategoryDTO | null>(null); // 用于存储选中的行数据

function handleUpdate(row: CategoryDTO) {
  selectedRow.value = row; // 保存选中的行数据
  updateForm.categoryId = row.categoryId;
  updateForm.parentId = row.parentId;
  updateForm.categoryName = row.categoryName;
  updateDialogOpen.value = true;
}

function handleSubmitUpdate() {
  updateFormRef.value?.validate(valid => {
    if (valid) {
      const data = {
        categoryId: updateForm.categoryId,
        parentId: updateForm.parentId,
        categoryName: updateForm.categoryName
      };
      console.log("即将发送的请求:", {
        method: "put",
        url: "/api/category",
        data
      });
      updateCategory(data)
        .then(() => {
          ElMessage.success("修改成功");
          updateDialogOpen.value = false;
          getList();
        })
        .catch(() => {
          ElMessage.error("修改失败");
        });
    }
  });
}

// 数据操作区--> 批量删除
function handleDeleteBatch() {
  const categoryIds = ids.value;
  if (categoryIds.length === 0) {
    ElMessage.error("请至少选择一个产品进行删除");
    return;
  }
  ElMessageBox.confirm("是否删除选中的数据?", "警告")
    .then(() => {
      return deleteCategoryBatch(categoryIds); //批量删除接口
    })
    .then(() => {
      getList(); // 重新加载数据
      ElMessage({ type: "success", message: "批量删除成功" });
    })
    .catch(() => {}); // 捕捉取消操作
}

/** ------------------删除弹框-------------------- */
const deleteDialogOpen = ref<boolean>(false);
const deleteForm = reactive({
  categoryId: 0,
  parentName: "",
  categoryName: ""
});

function handleDelete(row: CategoryDTO) {
  deleteForm.categoryId = row.categoryId;
  deleteForm.parentName = row.parentName;
  deleteForm.categoryName = row.categoryName;
  deleteDialogOpen.value = true;
}

function handleSubmitDelete() {
  ElMessageBox.confirm("是否确认删除?", "警告", {
    confirmButtonText: "是",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteCategory(deleteForm.categoryId)
        .then(() => {
          ElMessage.success("删除成功");
          deleteDialogOpen.value = false;
          getList();
        })
        .catch(() => {
          ElMessage.error("删除失败");
        });
    })
    .catch(() => {
      deleteDialogOpen.value = false;
    });
}

/** ------------------查看弹框-------------------- */
const drawer = ref<boolean>(false);
const categoryTitle = ref<string>("");
const category = ref<CategoryDTO>({
  categoryId: 0,
  categoryName: "",
  parentName: "",
  parentId: 0,
  createTime: undefined
});

async function handleView(row: CategoryDTO) {
  console.log("查看的类别数据：", row); // 调试输出

  // 如果 parentId 存在，调用 getCategoryById 获取父类别的 categoryName
  if (row.parentId) {
    try {
      const parentCategory = await getCategoryById(row.parentId);
      console.log("父类别数据：", parentCategory); // 调试输出
      row.parentName = parentCategory.data.categoryName; // 将父类别的 categoryName 赋值给 parentName
    } catch (error) {
      console.error("获取父类别失败：", error);
      ElMessage.error("获取父类别失败");
    }
  }

  category.value = row;
  categoryTitle.value = "查看类别[" + row.categoryId + "]";
  drawer.value = true;
}
</script>
